//
//  PictureBrowserCollectionViewCell.swift
//  Whiteboard
//
//  Created by point on 2018/1/10.
//  Copyright © 2018年 point. All rights reserved.
//

import UIKit
import Kingfisher
import SnapKit

protocol PictureBrowserCollectionViewCellDelegate: class {
    func pictureBrowserCollectionViewCellDissMiss()
}


class PictureBrowserCollectionViewCell: UICollectionViewCell {
    
    fileprivate let maxScale: CGFloat = 10.0 // 最大的缩放比例
    fileprivate let minScale: CGFloat = 1.0 // 最小的缩放比例
    fileprivate lazy var progressView : ProgressView = ProgressView()
    weak var delegate:PictureBrowserCollectionViewCellDelegate?
    fileprivate lazy var scrollView : UIScrollView = {
        let  scrollView = UIScrollView()
        scrollView.delegate = self
        return scrollView
    }()
    lazy var imgView:UIImageView  = UIImageView()
    var imgViewResetFrame:CGRect = CGRect.zero
    fileprivate var isScale: Bool = false
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


// MARK:- 数据源
extension PictureBrowserCollectionViewCell {
    
    func config(model:String)  {
        
        guard let _ = URL(string: model) else {
            return
        }
        
        let cache = KingfisherManager.shared.cache
        let img = cache.retrieveImageInDiskCache(forKey: model)
        if (img != nil) {
            let img:UIImage = img!
            imgViewResetFrame = img.formatImageSizeTwo(size: CGSize(width: img.size.width, height: img.size.height))
            imgView.frame = imgViewResetFrame
            imgView.showImageI(model)
        }else {
            progressView.isHidden = false
            progressView.progress = 0.1
            KingfisherManager.shared.downloader.downloadImage(with: URL(string:model)!, options: nil, progressBlock: {[weak self](receivedSize, totalSize) in
                let progress:CGFloat = CGFloat(receivedSize / totalSize)
                self?.progressView.progress = progress
                }, completionHandler: {[weak self](_ image: Image?, _ error: NSError?, _ url: URL?, _ originalData: Data?) in
                    self?.progressView.isHidden = true
                    guard image != nil else {
                        //self?.getViewController()?.hudLoadJuHua()
                        return
                    }
                    
                    
                    let img:UIImage = image!
                    self?.imgViewResetFrame = img.formatImageSizeTwo(size: CGSize(width: img.size.width, height: img.size.height))
                    self?.imgView.frame = (self?.imgViewResetFrame)!
                    self?.imgView.showImageI(model)
            })
        }
    }
}

// MARK:- 缩放
extension PictureBrowserCollectionViewCell: UIScrollViewDelegate {
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return self.imgView;
    }
    
    func scrollViewDidZoom(_ scrollView: UIScrollView) {
        let offsetX: CGFloat = (scrollView.bounds.size.width > scrollView.contentSize.width) ? (scrollView.bounds.size.width - scrollView.contentSize.width) * 0.5 : 0.0
        let offsetY: CGFloat = (scrollView.bounds.size.height > scrollView.contentSize.height) ? (scrollView.bounds.size.height - scrollView.contentSize.height) * 0.5 : 0.0
        imgView.center = CGPoint(x: scrollView.contentSize.width * 0.5 + offsetX, y: scrollView.contentSize.height * 0.5 + offsetY)
    }
    
    func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) {
        let  vc:PictureBrowserViewController = getViewController() as! PictureBrowserViewController
        vc.collectionView.isScrollEnabled = false
    }
    
    func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
        let  vc:PictureBrowserViewController = getViewController() as! PictureBrowserViewController
        if scale == 1.0 {
            vc.collectionView.isScrollEnabled = true
        }else {
            vc.collectionView.isScrollEnabled = false
        }
    }
}

// MARK:- 手势
extension PictureBrowserCollectionViewCell:UIGestureRecognizerDelegate{
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        if (otherGestureRecognizer.view is UIScrollView) {
            return true
        }else {
            return false
        }
    }
    
    @objc func tapFunc(ges:UITapGestureRecognizer) {
        
        if ( scrollView.zoomScale == 1.0 ) {
            dissMiss()
        }else {
            isScale = false
            scrollView.setZoomScale(1, animated: true)
        }
    }
    
    @objc func tapFuncDouble(ges:UITapGestureRecognizer) {
        if (!isScale) {
            isScale = true
            scrollView.setZoomScale(2, animated: true)
        }else {
            isScale = false
            scrollView.setZoomScale(1, animated: true)
        }
    }
    
    @objc func panFunc(ges:UIPanGestureRecognizer) {
        if scrollView.zoomScale == 1.0 { //只有在没缩放的时候才走手势
            let location: CGPoint = ges.translation(in: ges.view)
            if ges.state == .changed {
                imgView.y = imgView.y + location.y
                if imgView.y <= imgViewResetFrame.origin.y { //手势不能网上滑动
                    imgView.y = imgViewResetFrame.origin.y
                }
                ges.setTranslation(CGPoint.zero, in: ges.view)
                if imgView.centerY <= (kScreenH / 4.0 * 2.0) { //背景色改变
                    scrollView.backgroundColor = UIColor.black
                }else { //渐变背景色
                    let offsetY = imgView.centerY - (kScreenH / 2.0)
                    let progess:CGFloat = offsetY / (kScreenH / 2.0)
                    if (progess <= 1) {
                        scrollView.backgroundColor = UIColor.black.withAlphaComponent(1 - (1*progess))
                    }else {
                        scrollView.backgroundColor = UIColor.black
                    }
                }
            }
            
            if (ges.state == .ended) {
                if imgView.centerY >= (kScreenH / 4.0 * 3.0) {
                    dissMiss()
                }else {
                    UIView.animate(withDuration: 0.5, animations: {
                        self.imgView.frame = self.imgViewResetFrame
                        self.scrollView.backgroundColor = UIColor.black
                    })
                }
            }
        }else {  //还在缩放的状态
            
        }
    }
}




// MARK:- 设置UI
extension PictureBrowserCollectionViewCell {
    fileprivate func setupUI() {
        let frame = CGRect(x: 0, y: 0, width: kScreenW, height: kScreenH)
        scrollView.frame = frame
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.maximumZoomScale = maxScale // scrollView最大缩放比例
        scrollView.minimumZoomScale = minScale // scrollView最小缩放比例
        scrollView.bounces = false
        scrollView.backgroundColor = UIColor.black
        scrollView.bouncesZoom = true
        contentView.addSubview(scrollView)
        
        progressView.bounds = CGRect(x: 0, y: 0, width: 50, height: 50)
        progressView.center = CGPoint(x: kScreenW * 0.5, y: kScreenH * 0.5)
        // 3.设置控件的属性
        progressView.isHidden = true
        progressView.backgroundColor = UIColor.clear
        scrollView.addSubview(progressView)
        scrollView.addSubview(imgView)
        self.progressView.progress = 0.0
        contentView.addSubview(progressView)
        
        
        
        
        //图片添加手势
        //单击
        imgView.isUserInteractionEnabled = true
        let tapGesutre = UITapGestureRecognizer(target: self, action:#selector(tapFunc(ges:)))
        tapGesutre.numberOfTapsRequired = 1
        tapGesutre.numberOfTouchesRequired = 1
        imgView.addGestureRecognizer(tapGesutre)
        scrollView.addGestureRecognizer(tapGesutre)
        
        
        //双击
        let tapDoubleGesutre = UITapGestureRecognizer(target: self, action: #selector(tapFuncDouble(ges:)))
        tapDoubleGesutre.numberOfTapsRequired = 2
        tapDoubleGesutre.numberOfTouchesRequired = 1
        tapGesutre.require(toFail: tapDoubleGesutre)
        imgView.addGestureRecognizer(tapDoubleGesutre)
        
        //拖动
        let panGesutre  = UIPanGestureRecognizer(target: self, action: #selector(panFunc(ges:)))
        imgView.addGestureRecognizer(panGesutre)
        panGesutre.delegate = self
    }
    
    func dissMiss()  {
        self.scrollView.backgroundColor = UIColor.clear
        delegate?.pictureBrowserCollectionViewCellDissMiss()
    }
}

